const _ = require('lodash');

const prefix = '/api/types';

module.exports = app => {
  const {router, model, middleware} = app;

  /** 所有平台 */
  router.get(prefix + '/platforms', middleware.checkLogin, async ctx => {
    ctx.body = await model.Platform.findAll({where: {disabled: false}});
  });

  /** 搜索平台与直播类型 */
  router.get(prefix + '/search', middleware.checkLogin, async ctx => {
    const word = ctx.query.search;
    if (_.isEmpty(word))
      return ctx.helper.error('请输入关键字');
    ctx.body = await model.Type.findAll(
        {where: {name: {[app.Sequelize.Op.like]: '%' + word + '%'}}});
  });

  /** 创建直播类型 */
  router.post(prefix, middleware.checkLogin, async ctx => {
    const {name} = ctx.request.body;
    const [type] = await model.Type.findOrCreate(
        {where: {name}, defaults: {name}});
    ctx.body = type;
  });

  /** 读取分类与什么平台绑定 */
  router.get(prefix + '/:type_id(\\d+)', middleware.checkLogin, async ctx => {
    const {type_id} = ctx.params;
    const data = await model.PlatformType.findAll({where: {type_id}});
    ctx.body = data.map(platform => platform.platform_id);
  });

  /** 将type与platform绑定 */
  router.get(prefix + '/bind/:platform_id(\\d+)/:type_id(\\d+)',
      middleware.checkLogin,
      async ctx => {
        const {type_id, platform_id} = ctx.params;

        //将type与platform绑定
        const [platform, type] = await Promise.all([
          model.Platform.findById(platform_id),
          model.Type.findById(type_id),
        ]);
        if (!type)
          return ctx.helper.error('不存在的直播类型');
        else if (!platform)
          return ctx.helper.error('不存在的直播平台');
        await model.PlatformType.findOrCreate(
            {where: {type_id, platform_id}, defaults: {type_id, platform_id}});
        ctx.body = 'ok';
      });
};

